<!---
 
  Copyright (c) 2010, Cristian Costantini - cristian@millemultimedia.it
  
  FileManager is licensed under the terms of the Open Source GPL 3.0 license. 
	
	http://www.gnu.org/licenses/gpl.html
  
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
--->

<cfsetting enablecfoutputonly="true">

<cfif thisTag.ExecutionMode eq "end">
	<cfexit>
</cfif>

<cfparam name="attributes.startPath" default="" />
<cfparam name="attributes.remoteServices"  default="#getDirectoryFromPath( cgi.script_name )#remote" />
<cfparam name="attributes.developmentmode" default="false" type="boolean" />

<cfset img = "" />
<cfset plugins = "" />
<cfset jslisteners =  "" />
<cfset serviceString = "services" />
<cfset serviceInit = "" />
<cfset listServices = "" />

<!--- @ objects --->
<cfset icon = request.fileManager.getDSPobjects().getIcon() />
<cfset script = request.fileManager.getDSPobjects().getScript() />
<cfset handler = request.fileManager.getDSPobjects().getHandler() />

<!--- coldfusion javascript service mappings --->
<cfdirectory action="list" directory="#expandPath( attributes.remoteServices )#" name="services" />

<cfloop query="services">

	<cfif listLast( services.name, '.' ) eq 'cfc'>
	
		<cfset meta = getComponentMetaData( "#replaceNoCase( replaceNoCase( attributes.remoteServices, "/", ".", "all" ), ".", "", "one" )#.#listFirst( services.name, '.' )#" ) />
		
		<cfset func = meta.functions />
		
		<cfset serviceInit = listAppend( serviceInit, serviceString & "." & lcase( listFirst( services.name, '.' ) ) & " = {};", chr(32) ) />
		
		<cfloop array="#func#" index="method">
		
			<cfif method.access eq "remote">
			
				<cfset listServices = listAppend( listServices, serviceString & "." & lcase( listFirst( services.name, '.' ) ) & "." & method.name & " = '#getDirectoryFromPath( cgi.script_name )#remote/#services.name#?method=#method.name#&returnformat=json';", chr(32) ) />
			
			</cfif>
		
		</cfloop>
		
	<cfelseif  listLast( services.name, '.') eq 'cfm'  >
		
		<cfset serviceInit = listAppend( serviceInit, serviceString & "." & lcase( listFirst( services.name, '.' ) ) & " = {};", chr(32) ) />
		
		<cfset listServices = listAppend( listServices, serviceString & "." & lcase( listFirst( services.name, '.' ) ) & " = '#getDirectoryFromPath( cgi.script_name )#remote/#services.name#';", chr(32) ) />
	
	</cfif>
	
</cfloop>

<cfset serviceMapping = '<script type="text/javascript">#chr(10)#		var services = {}; #serviceInit# #listServices##chr(10)#		</script>' />

<!--- plug-in listener mapping --->
<cfsavecontent variable="jslisteners">
<cfoutput>
<cfloop array="#handler#" index="i">
<cfif len( i.ddGroup )>
		pluginEventManager.addListener( '#i.target#', '#i.event#', #i.plugin#, '#i.ddGroup#');
<cfelse>
		pluginEventManager.addListener( '#i.target#', '#i.event#', #i.plugin#);
</cfif>
</cfloop>
</cfoutput>
</cfsavecontent>

<cfsavecontent variable="main">
<cfoutput>
		var currentFullPath = location.protocol + '//' + location.host + location.pathname;
	
		//handler messaggio errore json response
	    function errorLogHandler(jsonResponse){
			var createDirSuccess = Ext.Msg.show({title: 'Error',msg: 'An error as occured, see log for details',buttons: Ext.Msg.OK,maxWidth:300,minWidth:300});
			var log1 = document.getElementById("logArea").value;
			document.getElementById("logArea").value = getCurrentTime() + ' | '+ jsonResponse.message +'\n' + log1
		}
		
		function infoTable(file){
			var html = new Array();
			html.push('<table id=\"infoTable\"><tr><td>Name:</td><td>'+file.name+'</td></tr>');
			html.push('<tr><td>File type:</td><td>'+file.extension+'</td></tr>');
			html.push('<tr><td>Path:</td><td>'+file.relativepath+'</td></tr>');
			if(file.size >= 1024){
				html.push('<tr><td>Size:</td><td>'+Math.round(file.size/1024)+' Kb</td></tr>');
			}else{
				html.push('<tr><td>Size:</td><td>'+file.size+' byte</td></tr>');
			}
			html.push('<tr><td>Last modified:</td><td>'+file.datelastmodified+'</td></tr>');
			html.push('<tr><td>Read only:</td><td>');
			if(file.canwrite==1){
				html.push('False</td></tr>');
			}else{
				html.push('True</td></tr>');
			}
			
			if(file.extension == 'jpg' || file.extension == 'png' || file.extension == 'gif' || file.extension == 'tiff' || file.extension == 'bmp'){
				html.push('<tr class="previewRow"><td>Preview:</td><td><img src=\"'+file.relativepath+'\" class=\"infoBoxPreview\" alt=\"'+file.name+'\"/></td></tr>');
			}
			if(file.extension == 'mp4' || file.extension == 'ogg' || file.extension == 'ogv' || file.extension == 'wmv' || file.extension == 'mov'){
				html.push('<tr class="previewRow"><td>Preview:</td><td><embed src=\"../'+file.relativepath+'\" width=\"300\"/></td></tr>')
			}
			html.push('</table>');
			return html;
		}
		
		//get current time
		function getCurrentTime(){
				var currentTime = new Date();
				var hours = currentTime.getHours()
				var minutes = currentTime.getMinutes()
				if (minutes < 10){
					minutes = "0" + minutes;
				}
				var month = currentTime.getMonth() + 1;
				var day = currentTime.getDate();
				var year = currentTime.getFullYear();
				
				var time = day+"/"+month+"/"+year+" - "+hours+":"+minutes;
				
				
				return time;
			}
			
		function createMBox(){
			mBox = Ext.MessageBox;
			Ext.Ajax.on('beforerequest', function(){
				mBox.wait('Processing...');
			});
			
			Ext.Ajax.on('requestcomplete', function(){
				mBox.hide();
			});
			
			Ext.Ajax.on('requestexception', function(){
				mBox.hide();
			});
		}
		
		Ext.Ajax.request({
			url: services.filemanager.getIcoExtensionList,
			method: 'post',
			success: function(result,request){
				iconsSet = eval(result.responseText);
			}
		});
		
		
		//	UI Object
		var _FileGridPanel = new fileManager.ui.FileGridPanel( services.filemanager.getFiles );
		var _DirTrePanel = new fileManager.ui.DirTreePanel( services.filemanager.getDirectories );
		var _DirectoryFormPanel = new fileManager.ui.DirectoryFormPanel( services.filemanager.getDirectories );
		var _UploadFormPanel = new fileManager.ui.UploadFormPanel( '' );
		
		
		//	Listeners
		_DirTrePanel.addListener( 'click', function( node ){
				
				//pagination param
				_FileGridPanel.store.on({
				    'beforeload': {
						fn: function(store, options){
							Ext.apply(options.params, {
								node: node.id
							});
						}
					}
				 });
				//pagination param
				
				_FileGridPanel.store.load({
					params: {
						node: node.id
					}
				});
				currentDir=node.id;
				_UploadFormPanel.getForm().findField('destinationPath').setValue("/"+node.id);
				
				Ext.getDom('directoryPath').value = node.id;			
				//Ext.getDom('filePath').value = node.id;
			
		});
	
		_DirTrePanel.addListener( 'dblclick', function( node ){
			
		});
		
		_DirTrePanel.addListener( 'expandnode', function( node ){
			if (node.id != 'source') {
				_FileGridPanel.store.load({
					params: {
						node: node.id
					}
				});
			}
		});
		
		_DirTrePanel.addListener( 'movenode', function( tree, node, oldParent, newParent, index ){
			
			Ext.Ajax.request({
				url:services.filemanager.moveDirectory,
				method:'post',
				params:{
					source:"/"+node.id,
					destination:"/"+newParent.id+"/"+node.text
				},
				success:function(result,request){
					var jsonResponse = Ext.util.JSON.decode(result.responseText);
					if (jsonResponse.success == true) {
						var log1 = document.getElementById("logArea").value;
						document.getElementById("logArea").value = getCurrentTime()+' | Directory '+node.id+' moved to folder '+newParent.id+'\n' + log1;
						node.id="/"+newParent.id+"/"+node.text;
					}else{
						errorLogHandler(jsonResponse);
					}
				}
			});
			
			
		});
		
		_DirectoryFormPanel.getForm().addListener( 'actioncomplete', function(){
			_DirTrePanel.getRootNode().reload();
			_DirectoryFormPanel.getForm().reset();
		});
		
		_UploadFormPanel.getForm().addListener( 'actioncomplete' , function(){
			_FileGridPanel.store.reload({});
			_UploadFormPanel.getForm().reset();
		});
		
		
		//Move File gridToTree Drag and drop
		_DirTrePanel.addListener('beforenodedrop',function(e){
			if(Ext.isArray(e.data.selections)){
					e.cancel = false;
					for(var i=0;i<e.data.selections.length;i++){
						rowToMove=e.data.selections[i];
						destinationDir=e.target.id;
						if(rowToMove.data.canwrite==true){
							Ext.Ajax.request({
								url: services.filemanager.moveFile,
								method: 'post',
								params: {
									source: "/" + rowToMove.data.relativepath,
									destination: "/" + destinationDir
								},
								success:function(result,request){
									var jsonResponse = Ext.util.JSON.decode(result.responseText);
									if (jsonResponse.success == true) {
										var log1 = document.getElementById("logArea").value;
										document.getElementById("logArea").value = getCurrentTime()+' | File '+rowToMove.data.relativepath+' moved to folder '+destinationDir+'\n' + log1;
									}else{
										errorLogHandler(jsonResponse);
									}
								}
							});
							
						}else{
							var createDirSuccess = Ext.Msg.show({title: 'Error',msg: 'Permission required',buttons: Ext.Msg.OK,maxWidth:300,minWidth:300});
						}
					}
				}
			_FileGridPanel.store.reload({});
		});
		
		var messageLog = new Ext.form.TextArea({	
			height:73,
			preventScrollbars: false,
			style:{overflow:'scroll',width:'100%'},
			id: 'logArea',
			readOnly: true
		});
	
		// Tree right click context menu
		var contextMenu = new Ext.menu.Menu({
			items:[
				{
					text:'Copy',
					handler: function(){
						copyPasteHandler(_DirTrePanel.getSelectionModel().getSelectedNode().id, 'directory');
					}
				}
	,
			{
				text: 'Delete',
				handler: function(){
					Ext.Msg.show(
					{
						title:'Delete directory '+_DirTrePanel.getSelectionModel().getSelectedNode().id,
						msg:'Are you sure?',
						width:300,
						height:200,
						buttons:{
							yes:true,
							no:true,
							cancel:false
						},
						fn: function(btn){
							switch(btn){
								case 'yes':
									var log1 = document.getElementById("logArea").value;
									document.getElementById("logArea").value = getCurrentTime()+' | Directory '+_DirTrePanel.getSelectionModel().getSelectedNode().id+' deleted from disk\n' + log1;
									Ext.Ajax.request({
										url:services.filemanager.deleteDirectory,
										method:'post',
										params:{
											directoryPath:"/"+_DirTrePanel.getSelectionModel().getSelectedNode().id
										}
									});
									_DirTrePanel.getSelectionModel().getSelectedNode().remove();
								break;
								case 'no':
									
								break;
							}
						}
					}
					);
				}
			}
	
			]
		});
		
		_DirTrePanel.on('contextMenu',treeContextHandler);
	
		function treeContextHandler(node){
			node.select();
			contextMenu.show(node.ui.getAnchor());
		}
			
		//grid right click context menu
		
		_FileGridPanel.addListener('rowcontextmenu',gridContextHandler);
		function gridContextHandler(grid,rowindex,e){
			
			e.stopEvent();
			var selectedFile = rowindex;
			
			var gridContextMenu = new Ext.menu.Menu();
			var index = rowindex;
			
			if (index != null) {
				gridContextMenu.add(
				{
					text:'Download',
					handler:function(){
						var rec = grid.store.getAt(index);
						var download = rec.data.relativepath;
						
						window.open( services.filemanager.download + "&download=" + download );
					}
				},
				{
					text:'Copy',
					handler: function(){
						copyPasteHandler(grid.store.getAt(index).data.relativepath, 'file');
					}
				},
				{
					text: "Delete",
					handler:function(){
						var rec = grid.store.getAt(index);
						if (rec.data.canwrite != false) {
							Ext.Msg.show({
								title: 'Delete file ' + rec.data.name,
								msg: 'Are you sure?',
								width: 300,
								height: 200,
								buttons: {
									yes: true,
									no: true,
									cancel: false
								},
								fn: function(btn){
									switch (btn) {
										case 'yes':
											var log1 = document.getElementById("logArea").value;
											document.getElementById("logArea").value = getCurrentTime()+' | File '+rec.data.name+' deleted from disk\n' + log1;
											Ext.Ajax.request({
												url: services.filemanager.deleteFile,
												method: 'post',
												params: {
													filepath: "/" + rec.data.relativepath
												}
											});
											grid.store.remove(rec);
											break;
										case 'no':
											
											break;
									}
								}
							});
						}else{
							Ext.Msg.show({title: 'Error',msg: 'This file is under write protection',buttons: Ext.Msg.OK,maxWidth:300,minWidth:300});
								
						}	
					}
					
				},{
					text: 'Properties',
					handler: function(){
						
						var rec = grid.store.getAt(index);
						var infoBox = new Ext.Window({
							title: rec.data.name,
							width:600,
	    					
							closable: true,
							plain:true,
							items: [{
								xtype:'panel',
								html: infoTable(rec.data)
							}]
						});
						infoBox.show(this);
					}
				});
				gridContextMenu.showAt(e.xy);
			}
		}
		
		// Copy Paste Handler
		function copyPasteHandler(copyC,copyT){
					
			copyContent = copyC;
			copyType = copyT;
			
			if(clipboardFull != true){
				
				contextMenu.add(
				{
					text:'Paste',
					handler:function(){
						switch(copyType){
							case 'file':
								copyDestination = "/"+_DirTrePanel.getSelectionModel().getSelectedNode().id;
								Ext.Ajax.request({
									url: services.filemanager.copyFile,
									method: 'post',
									params: {
										source: "/"+copyContent,
										destination: copyDestination
									},
									success: function(result,request){
										var jsonResponse = Ext.util.JSON.decode(result.responseText);
										if (jsonResponse.success == true) {
											_FileGridPanel.store.reload({});
											var log1 = document.getElementById("logArea").value;
											document.getElementById("logArea").value = getCurrentTime() + ' | File ' + copyContent + ' copied in ' + copyDestination + '\n' + log1;
										}else{
											errorLogHandler(jsonResponse);
										}
									},
									failure: function(){
										Ext.Msg.show({title: 'Error',msg: 'Error during file copy',buttons: Ext.Msg.OK,maxWidth:300,minWidth:300});
									}
								});
								
							break;
							case 'directory':
								copyDestination = "/"+_DirTrePanel.getSelectionModel().getSelectedNode().id;
								var dirName = copyContent.substring(copyContent.lastIndexOf("/"),copyContent.length);
								
								Ext.Ajax.request({
									url: services.filemanager.createDirectory,
									method: 'post',
									params: {
										directoryPath: copyDestination + dirName
									},
									success: function(){
										Ext.Ajax.request({
											url: services.filemanager.copyDirectory,
											method: 'post',
											params: {
												source: "/" + copyContent,
												destination: copyDestination + dirName
											},
											success: function(result,request){
												var jsonResponse = Ext.util.JSON.decode(result.responseText);
												if (jsonResponse.success == true) {
												
													_DirTrePanel.getRootNode().reload();
													var log1 = document.getElementById("logArea").value;
													document.getElementById("logArea").value = getCurrentTime() + ' | Directory ' + copyContent + ' copied in ' + copyDestination + '\n' + log1;
												}else{
													errorLogHandler(jsonResponse);
												}
											
											},
											failure: function(){
												Ext.Msg.show({title: 'Error',msg: 'Error during directory copy',buttons: Ext.Msg.OK,maxWidth:300,minWidth:300});
											}
										});
									},
									failure: function(){
											Ext.Msg.show({title: 'Error',msg: 'Error during directory copy',buttons: Ext.Msg.OK,maxWidth:300,minWidth:300});
										}
								});
								
							break;
						}
					}
				});
				clipboardFull = true;
			}	
		}
		
		Ext.onReady(function(){
			
			var currentDir;
			Ext.state.Manager.setProvider( new Ext.state.CookieProvider() );
			
			var bookTpl = new Ext.Template(bookTplMarkup);
			
			
			
			var viewport = new Ext.Viewport({
			    layout:'border',
			    items:[
					new Ext.ProgressBar({
                    region:'north',
                    el: 'north',
                    height:32
                }),
			        {
			            region:'south',
			            contentEl: 'south',
			            split:false,
			            height: 100,
			            minSize: 100,
			            maxSize: 200,
			            title:'Message',
			            margins:'0 0 0 0',
						split:false,
						items: [
							messageLog
						]
			        },{
			            region:'east',
			            title: 'Applications',
			            collapsible: true,
		            	autoScroll:true,
			            split:true,
			            width: 170,
			            minSize: 200,
			            maxSize: 200,
			            layout:'fit',
			            margins:'0 5 0 0',
						items:[
							new Ext.Panel({
								autoScroll:true,
									items:[
										bookTpl
									]
								})
						]
			         },{
			            region:'center',
			            title: 'Files',
			            collapsible: false,
			            split:true,
			            layout:'fit',
						items:[
							_FileGridPanel
						]
			         },{
			            title: 'Directories',
						region:'west',
			            split:true,
						width:280,
						layout:'vbox',
						layoutConfig: {
						    align : 'stretch',
						    pack  : 'start'
						},
			            items:[
							_DirTrePanel,
							new Ext.Panel({
								height:250,
								items:[
									_DirectoryFormPanel,
									_UploadFormPanel
								]
							})
			            ]
			          }
			     ]
			});
			for(a = 0 ; a < pluginsId.length ; a++){
				new Ext.ToolTip({
					target: pluginsId[a],
					title: document.getElementById(pluginsId[a]).getAttribute('title'),
					maxWidth: 120
				});
				document.getElementById(pluginsId[a]).removeAttribute('title');
			}
			#jslisteners#
			
		setTimeout("Ext.select('##modalLoaderContainer').fadeOut();createMBox();",2000); /* loader modal fade out*/
		Ext.ux.ToastWindowMgr = {
	    positions: [] 
	};
	
	Ext.ux.ToastWindow = Ext.extend(Ext.Window, {
	    initComponent: function(){
	          Ext.apply(this, {
	              iconCls: this.iconCls || 'information',
	            width: 200,
	            height: 100,
	            autoScroll: true,
	            autoDestroy: true,
	            plain: false
	          });
	        this.task = new Ext.util.DelayedTask(this.hide, this);
	        Ext.ux.ToastWindow.superclass.initComponent.call(this);
	    },
	    setMessage: function(msg){
	        this.body.update(msg);
	    },
	    setTitle: function(title, iconCls){
	        Ext.ux.ToastWindow.superclass.setTitle.call(this, title, iconCls||this.iconCls);
	    },
	    onRender:function(ct, position) {
	        Ext.ux.ToastWindow.superclass.onRender.call(this, ct, position);
	    },
	    onDestroy: function(){
	        Ext.ux.ToastWindowMgr.positions.remove(this.pos);
	        Ext.ux.ToastWindow.superclass.onDestroy.call(this);
	    },
	    afterShow: function(){
	        Ext.ux.ToastWindow.superclass.afterShow.call(this);
	        this.on('move', function(){
	               Ext.ux.ToastWindowMgr.positions.remove(this.pos);
	            this.task.cancel();}
	        , this);
	        this.task.delay(4000);
	    },
	    animShow: function(){
	        this.pos = 0;
	        while(Ext.ux.ToastWindowMgr.positions.indexOf(this.pos)>-1)
	            this.pos++;
	        Ext.ux.ToastWindowMgr.positions.push(this.pos);
	        this.setSize(200,100);
	        this.el.alignTo(document, "br-br", [ -20, -20-((this.getSize().height+10)*this.pos) ]);
	        this.el.slideIn('b', {
	            duration: 1,
	            callback: this.afterShow,
	            scope: this
	        });    
	    },
	    animHide: function(){
	           Ext.ux.ToastWindowMgr.positions.remove(this.pos);
	        this.el.ghost("b", {
	            duration: 1,
	            remove: true,
	        scope: this,
	        callback: this.destroy
	        });    
	    }
	});  
    });
</cfoutput>
</cfsavecontent>

<!--- import all scripts and icon of plugin installed --->
<cfsavecontent variable="plugins">
<cfoutput>
	<cfloop array="#script#" index="i">
	<script type="text/javascript" src="#attributes.startPath#/fileManager/#i.src#"></script>
	</cfloop>
		<cfloop array="#icon#" index="i">
		<cfset img = listAppend( img, "'" & '<div id="#i.id#" title="#i.message#" style="float:left;"><img src="#attributes.startPath#/fileManager/#i.src#" height="40" width="40" style="margin:20px 30px;" /></div>' & "'", chr(44) ) />
		</cfloop>
	<script type="text/javascript">
	var	bookTplMarkup = [
		#img#
		];
	var pluginsId = ["#icon[1].id#"<cfloop index="i" from="2" to="#arrayLen(icon)#">,"#icon[i].id#"</cfloop>];
	</script>
</cfoutput>
</cfsavecontent>

<cfsavecontent variable="head">
<cfoutput>
	<link rel="stylesheet" type="text/css" href="#attributes.startPath#/fileManager/assets/ext/resources/css/ext-all.css" />
	<link rel="stylesheet" type="text/css" href="#attributes.startPath#/fileManager/assets/ui/ajax/file-upload.css" />
	<link rel="stylesheet" type="text/css" href="#attributes.startPath#/fileManager/assets/style/additionalStyle.css" />
	<script type="text/javascript">
	var fileManager = {};
	fileManager.ui = {};
	//clipboard variables
	var copyContent;
	var copyType;
	var copyDestination;
	var clipboardFull = false;
	</script>
	<!--- ext --->
 	<script type="text/javascript" src="#attributes.startPath#/fileManager/assets/ext/adapter/ext/ext-base.js"></script>
    <script type="text/javascript" src="#attributes.startPath#/fileManager/assets/ext/ext-all.js"></script>
	<!--- namespaces --->
	<script type="text/javascript">
	Ext.namespace('fileManager.plugin');
	Ext.namespace('fileManager.util');
	</script>
	#serviceMapping#
	<script type="text/javascript" src="#attributes.startPath#/fileManager/assets/ui/ajax/pluginEventManager.js"></script>
	<script type="text/javascript">
	var pluginEventManager = new fileManager.util.PluginEventManager();
	</script>
<cfif attributes.developmentmode >
	<script type="text/javascript" src="#attributes.startPath#/fileManager/assets/ui/dump.js"></script>
</cfif>
	<!--- import plugin libs --->
	#plugins#
	<script type="text/javascript">
	#main#
	</script>
	
	<!--- import adapter --->
	<script type="text/javascript" src="#attributes.startPath#/fileManager/assets/ui/ajax/TinyMCEadapter.js"></script>
	
</cfoutput>
</cfsavecontent>

<!--- file manager body --->
<cfsavecontent variable="body">
<cfoutput>
			<div id="modalLoaderContainer">
				<div id="modalLoaderBg">
					&nbsp;
				</div>
				<div id="modalLoader">
					<p>
						<img src="#attributes.startPath#/fileManager/assets/images/loadingBar.gif" alt="loading"/>
						<br/><br/>
						<span>Loading...</span>
					</p>
				</div>
			</div>
			<div id="west">
				
			</div>
			<div id="north">
			
			</div>
			<div id="center2">
				
			</div>
			<div id="center1">
			
			</div>
			<div id="south">
			
			</div>
</cfoutput>
</cfsavecontent>

<!--- output in tag head --->
<cfhtmlhead text="#head#" />

<cfoutput>
#body#
</cfoutput>
<cfsetting enablecfoutputonly="false">
<cfexit>